<?php
class M_challenge extends CI_Model {

	/**
	* This array contains information of challenge:
	* id			
	* owner_id			
	* name			
	* abstraction	
	* description	
	* status		
	* 
	* @var array contains the information about challenge
	*/
	var $info = array(); //Array with challenge information.
	
	function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * Function for checking if the challenge's name already exists in the database.
	 *
	 * @param string cName 
	 * @return bool TRUE if the challenge's name already exists, False if it do NOT exist.
	 */
	function challenge_exists($cName)
	{
		//get all challenges whose names are as $cName
		$query = $this->db->get_where('challenges', array('name' => $cName));
		
		//check if there are many challenges having the same input name
		if ($query->num_rows() > 1)
			die("Something went terrible wrong! Error 0002.");
		elseif ($query->num_rows() < 1)
			return FALSE; //there is no challenge having the given name
		else //num_rows == 1.
			return TRUE; //there is such challenge having the given name
	}
	
	/**
	 * Function for checking if an existing challenge's new name is already used in the database.
	 *
	 * @param string cName, cID
	 * @return bool TRUE if the name is available, FALSE otherwise.
	 */
	function challenge_name_available($cName, $cID)
	{
		//get all challenges whose names are as $cName
		$query = $this->db->get_where('challenges', array('name' => $cName, 'id !=' => $cID));
		
		//check if there are many challenges having the same input name
		if ($query->num_rows() > 1)
			die("Something went terrible wrong! Error 0002.");
		elseif ($query->num_rows() < 1)
			return TRUE; //there is no challenge having the given name
		else //num_rows == 1.
			return FALSE; //there is such challenge having the given name
	}
	
	/**
	 * Function for loading the information about the challenge from the database into the challenge object.
	 *
	 * @param int challenge_id The id of the challenge that are to be loaded.
	 * @return void
	 */
	 function load_challengedata($cID)
	{
		//Create the database query.
		$this->db->select('id, owner_id, name, abstract, description, status');
		$this->db->from('challenges');
		$this->db->where('id', $cID);
		
		//Fetching data about the challenge.
		$query = $this->db->get();
		
		//Making sure that there actually exist a challenge with the sent id.
		if ($query->num_rows() != 1) {
			die("Something went terrible wrong! Error 0004.");
		}
		
		//Loading data into the challenge object.
		$result = $query->result_array();
		$this->info = $result[0];
	}
		
	/**
	 * Function for returning information about a challenge.
	 *
	 * @param array parameters An array containing the names of the element to be returned from the challenge object variable.
	 * @return mixed Requested information about the challenge.
	 */
	function get_info($parameters)
	{
		//If no parameters was sent, then return false and abort.
		if (count($parameters) == 0) {
			return FALSE;
		}
		
		//Return false if the info array is empty (the object isn't loaded).
		if (empty($this->info)) {
			return FALSE;
		}
		
		//Creating an array for the return values.
		$return = array();
		
		//Going thru the parameters to see what to return.
		foreach ($parameters as $p)
		{
			//If the parameter sent correspond to a value in the object variable, then that value is loaded into the return array.
			switch ($p)
			{
				case 'all_info':
					return $this->info;
					break;
				case 'owner_id':
					$return['owner_id'] = $this->info['owner_id'];
					break;
				case 'name':
					$return['name'] = $this->info['name'];
					break;
				case 'abstract':
					$return['abstract'] = $this->info['abstract'];
					break;
				case 'description':
					$return['description'] = $this->info['description'];
					break;
				case 'status':
					$return['status'] = $this->info['status'];
					break;
				default:
					return FALSE;
					break;
			}
		}
		
		//If only one parameter is sent, then return only that value.
		if (count($return) == 1) {
			return $return[$parameters[0]];
		}
		
		//Returning values asked for.
		return $return;
	}
	
	/**
	 * Function for creating a challenge.
	 *
	 * @param array parameters Array containing the information about the challenge that are to be created.
	 * @return bool TRUE if the challenge was created, else FALSE.
	 */
	function create($parameters)
	{
		//Loading parameters into variables.
		$cName = $parameters['cName'];
		$cAbstract = $parameters['cAbstract'];
		$cDescription = $parameters['cDescription'];
		$cUserID = $parameters['cUserID'];
		$cStatus = $parameters['cStatus'];
				
		//Loading challenge info into the data array of the challenge object.
		$this->info['name']			= $cName;
		$this->info['abstract']		= $cAbstract;
		$this->info['description']	= $cDescription;
		$this->info['owner_id']		= $cUserID;
		$this->info['status']		= $cStatus;
		
		//TODO: need to check if inserting is successfully or not???
		
		//Inserting the new challenge into the database.
		$this->db->insert('challenges', $this->info);
		
		//Returning that the creation was successful.
		return TRUE;
	}
	
	function get_challenge_list($userID)
	{
		//Create the database query to get challenges the user own.
		$this->db->select('id, name, abstract, status');
		$this->db->from('challenges');
		$this->db->where('owner_id', $userID);
		//Stop creating the database query.
		
		//Fetching data.
		$query = $this->db->get();
		
		//Stores the challenges the user own.
		$own_challenges = $query->result_array();
		
		//Create the database query to get challenges the user participates in.
		$this->db->select('id, name, abstract, status');
		$this->db->from('challenges');
		$this->db->join('participation', 'participation.challenge_id = challenges.id');
		$this->db->where('participation.user_id', $userID);
		//Stop creating the database query.
		
		//Fetching data.
		$query = $this->db->get();
		
		//Stores the challenges the user participates in.
		$participate_challenges = $query->result_array();
		
		//Creates array that are to hold all challenges the user has connections to.
		$return = array();
		
		foreach ($own_challenges as $c) {
			//Adding the connection.
			$c['connection'] = 1; //1 = owner.
			
			//Adding the challenge to the final list.
			$return[] = $c;
		}
		
		foreach ($participate_challenges as $c) {
			//Adding the connection.
			$c['connection'] = 0; //0 = participant.
			
			//Adding the challenge to the final list.
			$return[] = $c;
		}
		
		return $return;
	}
	
	/**
	 * Function that returns a list of challenges that owner_id is $user_id
	 *
	 * @param $userID
	 * @return array The array with information of challenges that owner_id is $user_id
	 */
	function get_owner_challenge_list ($userID)
	{
		//Create the database query to get challenges the user own.
		$this->db->select('id, name, abstract, status');
		$this->db->from('challenges');
		$this->db->where('owner_id', $userID);
		//Stop creating the database query.
		
		//Fetching data.
		$query = $this->db->get();
		
		//Stores the challenges the user own.
		$own_challenges = $query->result_array();
		
		return $own_challenges;
	}
	
	/**
	 * Function that returns a list of challenges that the user participates in
	 *
	 * @param $userID
	 * @return array The array with information of challenges that the user participates in
	 */
	function get_participant_challenge_list ($userID)
	{
		//Create the database query to get challenges the user participates in.
		$this->db->select('id, name, abstract, status');
		$this->db->from('challenges');
		$this->db->join('participation', 'participation.challenge_id = challenges.id');
		$this->db->where('participation.participation_status', 1);
		$this->db->where('participation.user_id', $userID);
		//Stop creating the database query.
		
		//Fetching data.
		$query = $this->db->get();
		
		//Stores the challenges the user participates in.
		$participate_challenges = $query->result_array();
		
		return $participate_challenges;
	}
	
	
	/**
	 * Function that returns a list of all users and whatever or not they are participating in the challenge.
	 *
	 * @param void
	 * @return array The array with information about which users that are participating.
	 */
	function get_participants_list()
	{
		//Fetching users that are participating.
			//Create the database query.
			$this->db->select('user_id');
			$this->db->from('participation');
			$this->db->where('challenge_id', $this->info['id']);
			$this->db->where('participation_status', 0);
			$this->db->or_where('challenge_id', $this->info['id']);
			$this->db->where('participation_status', 1);
			//Stop creating the database query.
			
			//Fetching data about the users.
			$query = $this->db->get();
			
			//Saving the result array containing the users participating.
			$in_challenge = $query->result_array();
		
		//Fetching all users.
			//Create the database query.
			$this->db->select('id as user_id');
			$this->db->from('users');
			//Stop creating the database query.
			
			//Fetching data about the users.
			$query = $this->db->get();
			
			//Saving the result array containing all users
			$all_users = $query->result_array();
		
		//Creating an temporary array that will contain the user id:s as keys and the participation (true or false) as the value.
		$temp = array();
		
		//Making $temp containing the user id:s as keys and the particiation as a bool (standard is NOT participating).
		foreach ($all_users as $user) {
			$temp[$user['user_id']] = FALSE;
		}
		
		//Going thru the array of participants and setting their participation to TRUE in the temp array.
		foreach ($in_challenge as $user) {
			$temp[$user['user_id']] = TRUE;
		}
		
		//Finaly, the owner is set as participant.
		$temp[$this->info['owner_id']] = TRUE;
		
		//Converting the temp array to an array where each "array object" contains of the user id and the participation (this so the array returned is in the same format as if it was fetched from the database).
			//Creating an array that will contain the keys of the temp array, eg the user id:s.
			$keys = array_keys($temp);
			
			//Creating an array that are to contain the infromation in the final format.
			$return = array();
			
			//Going thru the keys array so the user id and the participation value could be put into the return array.
			foreach ($keys as $user_id) {
				$return[] = array(	'user_id'		=> $user_id,
									'participation'	=> $temp[$user_id]
									);
			}
		
		//Returning the list of users and their participation.
		return $return;
	}
	
	/**
	 * Function that adds a user to the challenge.
	 *
	 * @param array parameters Array containing information about how the user should be added to the challenge.
	 * @return bool TRUE if the user was added, FALSE if not.
	 */
	function add_participant($parameters)
	{
		//Checking that the user id is sent.
		if (!isset($parameters['user_id'])) {
			//The user id is essential for the adding so if not sent, return FALSE.
			return FALSE;
		}
		
		//If the user that are to be added is the owner then that user should not be added.
		if ($parameters['user_id'] == $this->info['owner_id']) {
			return FALSE;
		}
		
		//Checking that the user is actually added and not just updated from delete (for example).
			$query = $this->db->get_where('participation', array(	'challenge_id'	=> $this->info['id'],
																	'user_id'		=> $parameters['user_id'],
																	));
			
			//If there is more than one participation for a single user in a single challenge, then something in the database is corrupt.
			if ($query->num_rows() > 1) {
				die("Something went terrible wrong! Error 0003.");
			}
			//If the user already has a participation in the database then the adding is a question about updating.
			elseif ($query->num_rows() == 1) {
				return $this->update_participant(array(	'user_id'				=> $parameters['user_id'],
														'participation_status'	=> 0, //Pending
														//'invitation_status'		=> 0, 		// Vi: Pending invitation_status is removed from the database
														'invitation_date'		=> date('Y-m-d H:i:s') //Actual date.
														));
			}
		//Stop checking if the adding is a update.
		
		//Creating an array with the data of the adding.
		$data = array(	'challenge_id'	=> $this->info['id'],
						'user_id'		=> $parameters['user_id']
						);
		
		//Copying adding data from $parameters to $data (by doing this we know that only allowed elements exists in the data array).
		/*if (isset($parameters['invitation_status'])) {
			$data['invitation_status'] = $parameters['invitation_status'];
		}
		else {
			$data['invitation_status'] = 0; //Pending
		}*/ 			// Vi: invitation_status is removed from the database
		if (isset($parameters['participation_status'])) {
			$data['participation_status'] = $parameters['participation_status'];
		}
		else {
			$data['participation_status'] = 0; //Pending
		}
		if (isset($parameters['invitation_date'])) {
			$data['invitation_date '] = $parameters['invitation_date'];
		}
		else {
			$data['invitation_date '] = date('Y-m-d H:i:s'); //Actual date.
		}
		
		//Adding the user.
		$this->db->insert('participation', $data);
		
		//Return that the adding was successful.
		return TRUE;
	}
	
	/**
	 * Function that updates the participation (of a user) in the challenge.
	 *
	 * @param array parameters Array containing information about how the user's participation should be updated.
	 * @return bool TRUE if the operation was succesful, else FALSE.
	 */
	function update_participant($parameters)
	{
		//Checking that the user id is sent.
		if (!isset($parameters['user_id'])) {
			//The user id is essential for the updating so if not sent, return FALSE.
			return FALSE;
		}
		
		//If the user that are to be updated is the owner then that user should not be updated (because the owner should not exist in the participation table).
		if ($parameters['user_id'] == $this->info['owner_id']) {
			return FALSE;
		}
		
		//Loading the user id to a variable.
		$user_id = $parameters['user_id'];
		
		//Creating an array that are to store the data about the update.
		$data = array();
		
		//Copying updating data from $parameters to $data (by doing this we know that only allowed elements exists in the data array).
		/*if (isset($parameters['invitation_status'])) {
			$data['invitation_status'] = $parameters['invitation_status'];
		}*/			// Vi: invitation_status is removed from the database
		if (isset($parameters['participation_status'])) {
			$data['participation_status'] = $parameters['participation_status'];
		}
		if (isset($parameters['invitation_date'])) {
			$data['invitation_date '] = $parameters['invitation_date'];
		}
		
		//Updating the participation
		$this->db->where('challenge_id', $this->info['id']);
		$this->db->where('user_id', $user_id);
		$this->db->update('participation', $parameters);
		
		//Return that the operation was successful.
		return TRUE;
	}
	
	/**
	 * Function that converts the status of a challenge from a int to a human readable string.
	 *
	 * @param optional int status The status.
	 * @return string The human readable status.
	 */
	function convert_status($status = FALSE)
	{
		//Checking if the objects own status should be used.
		if ($status === FALSE) {
			$status = $this->info['status'];
		}
		
		switch ($status)
		{
			case 1:
				return 'Active';
				break;
			case 2:
				return 'Finished';
				break;
			case 3:
				return 'Deleted';
				break;
			default:
				return 'Inactive';
		}
	}
	
	/**
	 * Function that converts the description of a challenge from a text string to a HTML string.
	 * That means returning a string that web browsers can read correctly, eg linebreaks being converted to <br />.
	 *
	 * @param optional string description The string.
	 * @return string The string as HTML.
	 */
	function convert_description($description = FALSE)
	{
		//Checking if the objects own status should be used.
		if ($description === FALSE) {
			$description = $this->info['description'];
		}
		
		//Converting double linebreaks to paragraphs.
		$to_replace		= "\r\n\r\n";
		$replace_with	= '</p><p>';
		$description	= str_replace($to_replace, $replace_with, $description);
		
		//Converting remaining (single) linebreaks to breaks.
		$to_replace		= array("\r\n", "\n", "\r");
		$replace_with	= '<br />';
		$description	= str_replace($to_replace, $replace_with, $description);
		
		//Adding double linebreaks after paragraphs to do the HTML code more readable.
		$to_replace		= '</p><p>';
		$replace_with	= '</p>' . PHP_EOL . PHP_EOL . '<p>';
		$description	= str_replace($to_replace, $replace_with, $description);
		
		//Adding single linebreaks after breaks to do the HTML code more readable.
		$to_replace		= '<br />';
		$replace_with	= '<br />' . PHP_EOL;
		$description	= str_replace($to_replace, $replace_with, $description);
		
		//Return the converted string.
		return $description;
	}
		
	function delete ($challengeID)
	{
//		//delete all ch_participation objects
//		$this->db->delete('participation', array('challenge_id' => $challengeID));
//		
//		//delete all ch_contribution objects
//		$sql = "DELETE c FROM ch_contribution c
//  				JOIN ch_task t ON c.task_id = t.id
//  				WHERE t.challenge_id = ?";
//		$this->db->query($sql, array($challengeID));
//		
//		/*$this->db->where('task.challenge_id', $challengeID);
//		$this->db->where('task.id', 'contribution.task_id');
//		$this->db->delete('contribution');*/
//		
//		//delete all ch_task objects
//		$this->db->delete('task', array('challenge_id' => $challengeID));				
				
		//delete the challenge
		$this->db->delete('challenges', array('id' => $challengeID));
		
		return TRUE;
	}
	
	function update ($params)
	{
		//get the challenge's id
		$id = $params['cID'];
		
		//Creating an array of update info
		$data = array();
				
		//Copying updating data from $parameters to $data to enssure that only allowed elements exists in the data array).
		if (isset($params['cName'])) 
		{
			$data['name'] = $params['cName'];
		}
		if (isset($params['cAbstract'])) {
			$data['abstract'] = $params['cAbstract'];
		}
		if (isset($params['cDescription'])) {
			$data['description '] = $params['cDescription'];
		}
		if (isset($params['cStatus'])) {
			$data['status '] = $params['cStatus'];
		}
		
		//Updating the participation
		$this->db->where('id', $id);
		$this->db->update('challenges', $data);
		
		//Return that the operation was successful.
		return TRUE;
	}
	
	
	/**
	 * get the number of challenge invitations that the user hasnt deny or accept
	 *
	 * @param user_id
	 * @return get the number of challenge invitations that the user hasnt deny or accept
	 */
	function get_num_pending_invitation($userID)
	{
		$this->db->where('user_id', $userID);
		$this->db->where('participation_status', 0); //status = pending
		return $this->db->count_all_results('participation');		
	}
	
	
	/**
	 * get all challenges's info (id, name, abstract) that the user is invited to participate but hasnt confirmed
	 *
	 * @param user_id
	 * @return an array of challenges's info (id, name, abstract) that the user is invited to participate but hasnt confirmed
	 */
	function get_challenges_with_pending_invitation($userID)
	{
		$this->db->select('id, name, abstract');
		$this->db->from('challenges');
		$this->db->join('participation', 'participation.challenge_id = challenges.id');
		$this->db->where('participation.user_id', $userID);
		$this->db->where('participation.participation_status', 0);
		
		//Fetching data about the users.
		$query = $this->db->get();
			
		//Saving the result array containing all users
		return $query->result_array();		
	}	
	
	/**
	 * update user's participation on a challenge to "active" or delete the participation based on his invitation confirmation
	 *
	 * @param challenge_id, user_id, invitation confirmation
	 * @return bool TRUE
	 */
	function update_participation_status($challengeID, $userID, $status)
	{
		if ($status === "accept") //change the participation status to 1 [accept]
		{
			$data = array('participation_status' => 1);
			$this->db->where('challenge_id', $challengeID);
			$this->db->where('user_id', $userID);
			$this->db->update('participation', $data);
		}
		elseif ($status === "deny") //delete the participation object
		{
			$this->db->delete('participation', array('challenge_id' => $challengeID, 'user_id' => $userID));
		}
		
		return TRUE;
	}
	
	/**
	 * update user's participation on a challenge to active or delete the participation based on his invitation confirmation
	 *
	 * @param challenge_id, user_id, invitation confirmation
	 * @return bool TRUE
	 */
	function get_participation_statistic($challengeID)
	{
		//get the owner's id and name of the challenge
		$this->db->select('users.id as id, username');
		$this->db->from('users');
		$this->db->join('challenges', 'users.id = challenges.owner_id');
		$this->db->where('challenges.id', $challengeID);
		$ownerQuery = $this->db->get();
						
		if ($ownerQuery->num_rows() > 1)
		{
			die("Something went terrible wrong! Error 0006.");
		}
		$result = $ownerQuery->result_array();
		$owner = $result[0];
		
		// get all the task_id of the challenge
		$this->db->select('id');
		$this->db->from('task');
		$this->db->where('challenge_id', $challengeID);
		$taskQuery = $this->db->get();
		
		// get a list of users that are participating in the challenge
		$this->db->select('id, username');
		$this->db->from('users');
		$this->db->join('participation', 'users.id = participation.user_id');
		$this->db->where('participation.challenge_id', $challengeID);
		$this->db->where('participation.participation_status', 1); //status == 1[active] means the the user is participating in the challenge
		$paticipantQuery = $this->db->get();
		
		//an array of contribution summary of the owner and participants. 
		//each element is the number of task done by a participant/owner
		$contributionResult = array();
			
		if ($paticipantQuery->num_rows() > 0 && $taskQuery->num_rows() > 0) 
		{
			//put query result into an array
			$taskIDs = $taskQuery->result_array();
			$participants = $paticipantQuery->result_array();
			
			//add the challenge's owner to the participantIDs array
			$participants[] = $owner;
			
			//for each participant try to find a corresponding contribution object for each task of the challenge
			foreach($participants as $par)
			{
				$num_done_tasks = 0;
				foreach($taskIDs as $taskID)
				{
					// try to get the contribution object
					$this->db->select('id');
					$this->db->from('contribution');
					$this->db->where('task_id', $taskID['id']);
					$this->db->where('owner_id', $par['id']);
					$contributionQuery = $this->db->get();
					
					if ($contributionQuery->num_rows() > 1)
					{
						die("Something went terrible wrong! Error 0006.");
					}
					elseif ($contributionQuery->num_rows() == 1) // the participant has completed the task
					{
						$num_done_tasks++;
					}					
				}
				$contributionResult[] = 
					array('id' => $par['id'], 'name' => $par['username'], 
						  'percentage' => round(($num_done_tasks/$taskQuery->num_rows()) * 100),2);
			}
		}		
		// there are some participants but no task in the challenge
		elseif ($paticipantQuery->num_rows() > 0 && $taskQuery->num_rows() == 0) //no task in the challenge		
		{
			//put query result into an array
			$participants = $paticipantQuery->result_array();
			//add the challenge's owner to the participantIDs array
			$participants[] = $owner;
		
			foreach($participants as $par)
			{
				// since there is no task, the contribution is all zero
				$contributionResult[] = 
					array('id' => $par['id'], 'name' => $par['username'], 
						  'percentage' => 0); 
			}
		}	
		// the owner is currently the only one participating in the challenge and there are some tasks
		elseif ($paticipantQuery->num_rows() == 0 && $taskQuery->num_rows() > 0) 
		{
			//put query result into an array
			$taskIDs = $taskQuery->result_array();
				
			$num_done_tasks = 0;
			foreach($taskIDs as $taskID)
			{
				// try to get the contribution object
				$this->db->select('id');
				$this->db->from('contribution');
				$this->db->where('task_id', $taskID['id']);
				$this->db->where('owner_id', $owner['id']);
				$contributionQuery = $this->db->get();
				
				if ($contributionQuery->num_rows() > 1)
				{
					die("Something went terrible wrong! Error 0006.");
				}
				elseif ($contributionQuery->num_rows() == 1) // the owner has completed the task
				{
					$num_done_tasks++;
				}					
			}
			$contributionResult[] = 
					array('id' => $owner['id'], 'name' => $owner['username'],  
						  'percentage' => round(($num_done_tasks/$taskQuery->num_rows()) * 100),2);
		}
		// the owner is the only one participating in the challenge and there is no task in that challenge
		elseif ($paticipantQuery->num_rows() == 0 && $taskQuery->num_rows() == 0)
		{
			$contributionResult[] = 
					array('id' => $owner['id'], 'name' => $owner['username'],  
						  'percentage' => 0);
		}

		return $contributionResult;
	}
	
	function get_all_task_info($challenge_id, $participant_id)
	{
		// get id and name of all tasks which belong to the challenge
		$this->db->select('id, name');
		$this->db->from('task');
		$this->db->where('challenge_id', $challenge_id);
		$taskQuery = $this->db->get();
		
		// an array storing the participant's current result of all tasks in the challenge
		$task_result = array();
		
		if ($taskQuery->num_rows() > 0)
		{
			//put query result into an array
			$tasks = $taskQuery->result_array();
			
			//get contribution object of each task
			foreach($tasks as $task)
			{
				// try to get the contribution object
				$this->db->select('id, link, title, comment');
				$this->db->from('contribution');
				$this->db->where('task_id', $task['id']);
				$this->db->where('owner_id', $participant_id);
				$contributionQuery = $this->db->get();
				
				if ($contributionQuery->num_rows() > 1)
				{
					die("Something went terrible wrong! Error 0007.");
				}
				elseif ($contributionQuery->num_rows() == 1) // the participant has completed the task
				{
					$result = $contributionQuery->result_array();
					$contribution = $result[0];
					$task_result[] = array(	'id'		=> $task['id'],
											'name'		=> $task['name'],
											'status'	=> "done",
											'link'		=> $contribution['link'],
											'title'		=> $contribution['title'],
											'comment'	=> $contribution['comment'] );
				}
				else //there is no contribution object == the participant hasn't completed the task
				{
					$task_result[] = array(	'id'		=> $task['id'],
											'name'		=> $task['name'],
											'status'	=> "not done",
											'link'		=> '',
											'title'		=> '',
											'comment'	=> '' );
				}					
			}
		}		
		return $task_result;
	}
	
	/**
	 * Function for checking if the challenge has already a task with that name.
	 *
	 * @param string task name, challeng id 
	 * @return bool TRUE if the challenge has a task with name already, False if it do NOT exist.
	 */
	function task_exists($tName, $challengeID)
	{
		//get all challenges whose names are as $cName
		$query = $this->db->get_where('task', array('name' => $tName, 'challenge_id' => $challengeID));
		
		//check if there are many tasks having the same input name
		if ($query->num_rows() > 1)
			die("Something went terrible wrong! Error 0008.");
		elseif ($query->num_rows() < 1)
			return FALSE; //there is no task in that challenge having the given name
		else //num_rows == 1.
			return TRUE; //there is such task in that challenge having the given name
	}
	
	function get_all_task($challengeID)
	{
		// get id, name, description of all tasks which belong to the challenge
		$this->db->select('id, name, description');
		$this->db->from('task');
		$this->db->where('challenge_id', $challengeID);
		$taskQuery = $this->db->get();
		
		//put query result into an array
		$tasks = $taskQuery->result_array();
		
		return $tasks;		
	}
	
	/**
	 * Based on the task ID, this function returns the id of the challenge the task belongs to.
	 *
	 * @param int task_id The ID of the task.
	 * @return int challenge_id The ID of the challenge.
	 */
	function get_challenge_id_from_task_id($task_id)
	{
		$query = $this->db->get_where('task', array('id' => $task_id));
		
		$result = $query->result_array();
		
		$challenge_id = $result[0]['challenge_id'];
		
		return $challenge_id;
	}
	
	function add_task ($params)
	{				
		//Creating an array of task info
		$data = array();
				
		//Copying updating data from $parameters to $data to enssure that only allowed elements exists in the data array).
		if (isset($params['name'])) 
		{
			$data['name'] = $params['name'];
		}
		if (isset($params['description'])) {
			$data['description'] = $params['description'];
		}
		if (isset($params['challenge_id'])) {
			$data['challenge_id'] = $params['challenge_id'];
		}
		
		//Inserting the new challenge into the database.
		$this->db->insert('task', $data);
		
		//Returning that the creation was successful.
		return TRUE;
	}
	
	function delete_task ($taskID)
	{
		//delete the task
		$this->db->delete('task', array('id' => $taskID));
		
		return TRUE;
	}
	
	/**
	 * Function for returning information about the contributions a user has done in a challenge.
	 *
	 * @param array parameters An array containing the task id and the user id.
	 * @return mixed Information about the user's contribution if such a contribution exists, else FALSE.
	 */
	function fetch_contribution($parameters)
	{
		//Fetching the user and task id:s.
		$task_id =	$parameters['task_id'];
		$user_id =	$parameters['user_id'];
		
		//Get the user's contribution for the task.
		$this->db->select('link, title, comment');
		$this->db->from('contribution');
		$this->db->where('task_id', $task_id);
		$this->db->where('owner_id', $user_id);
		
		//Running query.
		$query = $this->db->get();
		
		//If there are no contributions then FALSE is returned.
		if ($query->num_rows() != 1) {
			return FALSE;
		}
		
		//Returning the array with the information about the contribution.
		$return = $query->result_array();
		return $return[0];
	}
	
	/**
	 * Function for updating the contribution from a user.
	 *
	 * @param array parameters An array containing ID:s of the user and the task and the information to update.
	 * @return bool TRUE if the update was successful, else FALSE;
	 */
	function update_contribution($parameters)
	{
		//Loading parameters into variables.
		$task_id	= $parameters['task_id'];
		$user_id	= $parameters['user_id'];
		
		$link		= $parameters['link'];
		$title		= $parameters['title'];
		$comment	= $parameters['comment'];
		
		//Checking if there are any contribution allready.
		$query = $this->db->get_where('contribution', array(	'task_id'	=> $task_id,
																'owner_id'	=> $user_id));
		
		//Finding out if to update or insert.
		if ($query->num_rows() == 0) {
			//Insert:
			$data = array(	'link'		=> $link,
							'title'		=> $title,
							'comment'	=> $comment,
							'task_id'	=> $task_id,
							'owner_id'	=> $user_id);
			
			$this->db->insert('contribution', $data); 
		}
		elseif ($query->num_rows() == 1) {
			//Update:
			$data = array(	'link'		=> $link,
							'title'		=> $title,
							'comment'	=> $comment );
			
			$this->db->where(array(	'task_id'	=> $task_id,
									'owner_id'	=> $user_id));
			
			$this->db->update('contribution', $data); 
		}
		else {
			//Return that the update was unsuccessful.
			return FALSE;
		}
		
		//Returning that the update was sucessful.
		return TRUE;
	}
}











